<template>
  <Dialog :title="t('sendChatTeacher.title')" v-model="chatDialogVisible" width="800">
    <CardTitle class="block mb-[10px]" :title="t('sendChatTeacher.inputPlaceholder')" />
    <el-input
      v-model="textMessage"
      :autosize="{ minRows: 4 }"
      type="textarea"
      :placeholder="t('sendChatTeacher.inputPlaceholder')"
      :maxlength="200"
      show-word-limit
    />

    <CardTitle class="block mt-[10px]" :title="t('sendChatTeacher.sendMethod')" />
    <el-checkbox-group v-model="checkedMethod">
      <el-checkbox :label="t('sendChatTeacher.methodNotify')" value="notify" />
      <el-checkbox :label="t('sendChatTeacher.methodEmail')" value="email" />
      <el-checkbox :label="t('sendChatTeacher.methodSms')" value="sms" />
    </el-checkbox-group>

    <template #footer>
      <el-button
        @click="submitSend"
        type="primary"
        :disabled="formLoading || !userIds.length || !textMessage.trim() || !checkedMethod.length"
      >
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="chatDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <el-link :underline="false" type="primary" @click="showDialog" :disabled="userIds.length === 0">
    {{ t('sendChatTeacher.title') }}</el-link
  >
</template>

<script setup lang="ts">
import { CardTitle } from '@/components/Card'
import { sendSystemMessage } from '@/api/system/user'

defineOptions({ name: 'SendChatTeacher' })

const props = defineProps<{
  userIds: number[]
}>()

const { t } = useI18n()
const message = useMessage()

const chatDialogVisible = ref(false)
const formLoading = ref(false)

const textMessage = ref('')
const checkedMethod = ref(['notify', 'email', 'sms'])

const showDialog = () => {
  textMessage.value = ''
  checkedMethod.value = ['notify', 'email', 'sms']
  chatDialogVisible.value = true
}

const submitSend = async () => {
  try {
    await message.confirm(t('sendChatTeacher.confirm'))
  } catch {
    return
  }
  try {
    formLoading.value = true
    await sendSystemMessage({
      message: textMessage.value,
      method: checkedMethod.value,
      userIds: props.userIds
    })
    chatDialogVisible.value = false
    message.success(t('sendChatTeacher.success'))
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.select-student__wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}
</style>
